//
//  DTagsAnalysisViewController.swift
//  Drop
//
//  Created by hushaohua on 2018/2/9.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit
import CoreData

class DTagsAnalysisViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    lazy var tableView:UITableView = {
        var view:UITableView = UITableView(frame: self.view.bounds, style: .grouped);
        view.delegate = self;
        view.dataSource = self;
        return view;
    }();
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "TAG统计";
        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.white;
        self.view.addSubview(self.tableView);
        self.configTableView();
        self.configNormalNavigation();
        self.requestNewest();
    }
    
    lazy var editButton:UIButton = {
        var button:UIButton = UIButton(frame: CGRect(x:0,y:0,width:44,height:44));
        button.setTitle("编辑", for: .normal);
        button.setTitle("完成", for: .selected);
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16);
        button.setTitleColor(UIColor.gray, for: .normal);
        button.setTitleColor(UIColor.darkGray, for: .selected);
        button.addTarget(self, action: #selector(editButtonClicked(_:)), for: .touchUpInside);
        return button;
    }();
    lazy var cancelButton:UIButton = {
        var button:UIButton = UIButton(frame: CGRect(x:0,y:0,width:32,height:44));
        button.setTitle("取消", for: .normal);
        button.setTitle("全选", for: .selected);
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16);
        button.setTitleColor(UIColor.gray, for: .normal);
        button.addTarget(self, action: #selector(cancelButtonClicked(_:)), for: .touchUpInside);
        return button;
    }();
    
    @objc func editButtonClicked(_ sender:UIButton){
        if (!sender.isSelected){
            self.configEditNavigation();
        }else{
            self.configNormalNavigation();
            self.selectedAnalysisItems.sort(by: { (item1, item2) -> Bool in
                return item1.duration > item2.duration ? true : false;
            });
            self.setChartHeaderItems();
        }
        self.tableView.reloadData();
    }
    
    @objc func cancelButtonClicked(_ sender:UIButton){
        sender.isSelected = !sender.isSelected;
        self.selectedAnalysisItems.removeAll();
        if (!sender.isSelected){
            for item in self.analysisItems {
                self.selectedAnalysisItems.append(item);
            }
        }
        self.tableView.reloadData();
    }
    
    func configNormalNavigation() {
        let item = UIBarButtonItem(customView: self.editButton);
        self.tableView.allowsMultipleSelection = false;
        self.editButton.frame.size.width = 44;
        self.editButton.isSelected = false;
        self.navigationItem.rightBarButtonItems = [item];
    }
    func configEditNavigation() {
        let editItem = UIBarButtonItem(customView: self.editButton);
        self.tableView.allowsMultipleSelection = true;
        self.editButton.isSelected = true;
        self.editButton.frame.size.width = 32;
        let cancelItem = UIBarButtonItem(customView: self.cancelButton);
        self.navigationItem.rightBarButtonItems = [editItem, cancelItem];
    }
    
    lazy var tableHeaderView:UIView = {
        //DAnalysisHeaderView
        let view:UIView = UIView(frame: CGRect(x:0,y:0,width:self.view.bounds.width,height:110));
        view.addSubview(self.chartScollView);
        view.backgroundColor = UIColor.white;
        self.chartScollView.addSubview(self.chartHeaderView);
        return view;
    }();
    
    lazy var chartHeaderView:HBarChartView = {
        var chartHeaderView:HBarChartView = HBarChartView(frame:CGRect(x:10,y:0,width:self.view.bounds.width - 20,height:100));
//        chartHeaderView.disableValue = true;
        chartHeaderView.barConfig().barWidth = 20;
        chartHeaderView.barConfig().barSpace = 10;
        chartHeaderView.backgroundColor = UIColor.white;
        return chartHeaderView;
    }();
    lazy var chartScollView:UIScrollView = {
        var scrollView:UIScrollView = UIScrollView(frame: CGRect(x:0,y:10,width:self.view.bounds.width,height:100));
//        scrollView.backgroundColor = UIColor.green;
        scrollView.showsHorizontalScrollIndicator = false;
        scrollView.contentSize = CGSize(width:self.view.bounds.width, height:100);
        return scrollView;
    }();
    
    func configTableView() -> Void{
        self.tableView.tableHeaderView = self.tableHeaderView;
        self.tableView.tableFooterView = UIView();
        self.tableView.rowHeight = 44;
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        };
        self.tableView.sectionHeaderHeight = 32;
        self.tableView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 84, right: 0);
        self.tableView.register(DAnalysisTagTableViewCell.self, forCellReuseIdentifier: "Cell");
        self.tableView.register(DAnalysisTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: "Header");
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    var analysisItems:[DTagAnalysisItem] = [DTagAnalysisItem]();
    var selectedAnalysisItems:[DTagAnalysisItem] = [DTagAnalysisItem]();
    //MARK:-
    func requestNewest() -> Void{
        do{
            let tags = try HStoreManager.defaultManger().context.fetch(self.tagsRequest);
            for dict in tags {
                let interval:Int64 = dict.object(forKey: "intervals") as! Int64;
                let tag:DTagAnalysisItem = DTagAnalysisItem();
                tag.duration = interval;
                tag.count = dict.object(forKey: "count") as! Int32;
                tag.tagName = dict.object(forKey: "tag.name") as! String;
                tag.tagID = dict.object(forKey: "tag") as? NSManagedObjectID;
                self.analysisItems.append(tag);
            }
            self.analysisItems.sort(by: { (item1, item2) -> Bool in
                return item1.duration > item2.duration ? true : false;
            });
            for item in self.analysisItems {
                self.selectedAnalysisItems.append(item);
            }
            self.setChartHeaderItems();
            self.tableView.reloadData();
        }catch{
            let nserror = error as NSError
            fatalError("tags controller fetch error \(nserror), \(nserror.userInfo)")
        }
    }
    
    func setChartHeaderItems() -> Void{
        var chartItems:[HBarChartItem] = [HBarChartItem]();
        for item in self.selectedAnalysisItems {
            if (item.barItem == nil){
                let chartItem:HBarChartItem = HBarChartItem();
                chartItem.key = item.tagName;
                chartItem.value = item.duration;
                item.barItem = chartItem;
            }
            chartItems.append(item.barItem!);
        }
        self.chartHeaderView.chartItems = chartItems;
        var contentWidth = self.chartHeaderView.horizontalWidth;
        if (contentWidth < self.view.bounds.size.width - 20){
            contentWidth = self.view.bounds.size.width - 20;
        }
        self.chartHeaderView.frame.size.width = contentWidth;
        self.chartScollView.contentSize.width = contentWidth + 10 + 10;
    }
    
    //MARK:- NSFetchedResultsController
    lazy var tagsRequest:NSFetchRequest<NSDictionary> = {
        
        let beginDateExp = NSExpression(forKeyPath: "begin");
        let endDateExp = NSExpression(forKeyPath: "end");
        let beginSumExpression = NSExpression(forFunction: "sum:", arguments: [beginDateExp]);
        let endSumExpression = NSExpression(forFunction: "sum:", arguments: [endDateExp]);
        let countExpression = NSExpression(forFunction: "count:", arguments:[endDateExp]);
        let intervalExp = NSExpression(forFunction: "from:subtract:", arguments: [endSumExpression, beginSumExpression]);
        
        let intervalExpDesc = NSExpressionDescription();
        intervalExpDesc.name = "intervals";
        intervalExpDesc.expression = intervalExp;
        intervalExpDesc.expressionResultType = .integer64AttributeType;
        
        let countExpDesc = NSExpressionDescription();
        countExpDesc.name = "count";
        countExpDesc.expression = countExpression;
        countExpDesc.expressionResultType = .integer32AttributeType;
        
        let request:NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: "Drop");
        request.resultType = .dictionaryResultType;
        request.propertiesToFetch = ["tag", intervalExpDesc, countExpDesc, "tag.name"];
        request.propertiesToGroupBy = ["tag", "tag.name"];
        request.returnsDistinctResults = true;
        request.includesSubentities = false;
        
        request.predicate = NSPredicate(format: "tag != nil");
        let sorter = NSSortDescriptor(key: "tag", ascending: true);
        request.sortDescriptors = [sorter];
        return request;
    }();
    
    //MARK:- tableView
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (self.editButton.isSelected){
            return self.analysisItems.count;
        }else{
            return self.selectedAnalysisItems.count;
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 32;
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view:UITableViewHeaderFooterView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header")!;
        return view;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:DAnalysisTagTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! DAnalysisTagTableViewCell;
        var item:DTagAnalysisItem? = nil;
        if (self.editButton.isSelected){
            item = self.analysisItems[indexPath.row];
            let contains = self.selectedAnalysisItems.contains(where: { (aItem) -> Bool in
                return aItem.tagID == item!.tagID;
            });
            cell.accessoryType = contains ? .checkmark : .none;
        }else{
            cell.accessoryType = .disclosureIndicator;
            item = self.selectedAnalysisItems[indexPath.row];
        }
        
        cell.tagLabel.text = item!.tagName;
        cell.timeLabel.text = item!.durationString();

        return cell;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (self.editButton.isSelected){
            tableView.deselectRow(at: indexPath, animated: false);
            let selectedItem:DTagAnalysisItem = self.analysisItems[indexPath.row];
            let index:Int? = self.selectedAnalysisItems.index(where: { (item) -> Bool in
                return item.tagID == selectedItem.tagID;
            });
            let cell = tableView.cellForRow(at: indexPath);
            if (index != nil){
                self.selectedAnalysisItems.remove(at: index!);
                cell?.accessoryType = .none;
            }else{
                self.selectedAnalysisItems.append(selectedItem);
                cell?.accessoryType = .checkmark;
            }
            self.cancelButton.isSelected = (self.selectedAnalysisItems.count != self.analysisItems.count);
        }else{
            tableView.deselectRow(at: indexPath, animated: true);
            let item:DTagAnalysisItem = self.analysisItems[indexPath.row];
            self.gotoTagAnalysis(tag: item);
        }
    }
    
    func gotoTagAnalysis(tag:DTagAnalysisItem) -> Void{
        let controller = DTagAnalysisViewController(tag:tag);
        self.navigationController?.pushViewController(controller, animated: true);
    }

}
